package com.qianguo.buyer;


import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eva.androidlibrary.api.HttpRequestCallback;
import com.eva.androidlibrary.utils.TimeUtil;
import com.qianguo.buyer.base.BaseTitleActivity;
import com.qianguo.buyer.constant.BuyerKeys;
import com.qianguo.buyer.entity.DeliveryTime;
import com.qianguo.buyer.entity.OrderSN;
import com.qianguo.buyer.entity.ShopCar;
import com.qianguo.buyer.entity.ShopCarItem;
import com.qianguo.buyer.order.BuyerOrderDetailActivity;
import com.qianguo.buyer.widget.DeliveryTimeDialog;
import com.qianguo.buyer.widget.ListContentDialog;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;


/**
 * 订单详情确认页
 *
 * @author guxun
 * @date 2016-06-28 16:43
 */
@EActivity(R.layout.activity_shop_car_confirm_main)
public class OrderConfirmActivity extends BaseTitleActivity {

    @ViewById(R.id.rv_order_confirm)
    ListView mShopCarView;

    @Extra(BuyerKeys.EXTRA_KEY_ORDER_CONFIRM_CAR_IDS)
    ArrayList<String> mCartIDS;

    List<String> mDeliveryDay;
    int mTotalPrice, mDayKey;//商品总价
    String mUserRealName = "", mUserPhone = "", mUserAddress = "", mUserDeliveryTime = "1_5", mUserRemark = "";
    EditText mEtUserName, mEtUserPhone, mEtUseAddress, mEtUserRemark;
    TextView mTvAllPrice, mTvDayVal, mTvTimeVal;
    RelativeLayout mRlSendDay, mRlSendTime;
    DeliveryTime mDeliveryTimeData;//api获取的配送时间参数
    private List<ShopCarItem> mShopCarData = new ArrayList<>();
    private SimpleRecyclerCardAdapter mSimpleRecyclerAdapter;

    public static void jumpToShopCarDetail(Context context, ArrayList<String> cartIDS) {
        Intent intent = new Intent();
        intent.setClass(context, OrderConfirmActivity_.class);
        intent.putStringArrayListExtra(BuyerKeys.EXTRA_KEY_ORDER_CONFIRM_CAR_IDS, cartIDS);
        context.startActivity(intent);
    }

    @Click(R.id.tv_confirm_order)
    void confirmOrder() {
        checkUserInput();
        confirmShopCarOrder();

    }

    @UiThread(propagation = UiThread.Propagation.REUSE)
    void checkUserInput() {
        mUserRealName = mEtUserName.getText().toString();
        mUserPhone = mEtUserPhone.getText().toString();
        mUserAddress = mEtUseAddress.getText().toString();
        mUserRemark = mEtUserRemark.getText().toString();
    }

    @Override
    protected String getToolbarTitle() {

        return "确认订单";
    }

    @Override
    protected void initializeUI() {
        mSimpleRecyclerAdapter = new SimpleRecyclerCardAdapter(this);
        mShopCarView.setAdapter(mSimpleRecyclerAdapter);
        View headView = LayoutInflater.from(this).inflate(R.layout.item_order_confirm_head, null, false);
        mEtUserName = (EditText) headView.findViewById(R.id.et_order_user_name);
        mEtUserPhone = (EditText) headView.findViewById(R.id.et_order_user_phone);
        mEtUseAddress = (EditText) headView.findViewById(R.id.et_order_user_address);
        mEtUserRemark = (EditText) headView.findViewById(R.id.et_order_note);
        mRlSendDay = (RelativeLayout) headView.findViewById(R.id.rl_order_send_day);
        mRlSendTime = (RelativeLayout) headView.findViewById(R.id.rl_order_send_time);
        mTvAllPrice = (TextView) headView.findViewById(R.id.tv_product_all_price);
        mTvDayVal = (TextView) headView.findViewById(R.id.tv_order_send_day_val);
        mTvTimeVal = (TextView) headView.findViewById(R.id.tv_order_send_time_val);
        mTvDayVal.setText(TimeUtil.getDeliveryTime());
        mRlSendDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DeliveryTimeDialog.Builder(OrderConfirmActivity.this)
                        .setTimeType(DeliveryTimeDialog.TIME_DAY)
                        .title(getResources().getString(R.string.choose_delivery_data))
                        .setListCallback(new ListContentDialog.ListCallback() {
                            @Override
                            public void onSelection(int position, String val) {
                                mTvTimeVal.setText(getString(R.string.input_send_time));
                                mTvDayVal.setText(val);
                                mDayKey = position;
                            }
                        }).show();

            }
        });
        mRlSendTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DeliveryTimeDialog.Builder(OrderConfirmActivity.this)
                        .setTimeType(DeliveryTimeDialog.TIME_HOUR)
                        .setDeliveryTimeData(mDeliveryTimeData)
                        .setTimeDataClickListener(new DeliveryTimeDialog.TimeDataClickCallback() {
                            @Override
                            public void onSelection(int position, String str, String val) {
                                mTvTimeVal.setText(str);
                                mUserDeliveryTime = val;
                                showSnackBar(OrderConfirmActivity.this, val + "");
                            }
                        })
                        .setDayKey(mDayKey)
                        .title(getResources().getString(R.string.choose_delivery_time))
                        .content(mDeliveryDay).show();

            }
        });
        mShopCarView.addHeaderView(headView);
        getShopCarIndex();

        getDeliveryTimeData();
    }

    /**
     * 获取购物车列表
     */
    @Background
    void getShopCarIndex() {
        mApp.getApi().getShopCarIndex(mApp.getUser().getToken(), getCarIDStrings(), new HttpRequestCallback<ShopCar>() {
            @Override
            public void onSuccess(int code, String msg, ShopCar data) {
                mShopCarData.clear();
                mShopCarData.addAll(data.getGoods());
                mTotalPrice = data.getTotal_price();
                refreshUI();
            }


            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(OrderConfirmActivity.this, msg);
            }
        });
    }

    @UiThread(propagation = UiThread.Propagation.REUSE)
    void refreshUI() {
        mTvAllPrice.setText(mTotalPrice + "");
        mSimpleRecyclerAdapter.notifyDataSetChanged();
    }

    private String getCarIDStrings() {
        String carID = "";
        for (String str : mCartIDS) {
            carID += str + ",";
        }
        return carID;
    }

    /**
     * 确认订单
     */
    @Background
    void confirmShopCarOrder() {
        showLoadingDialog(this);
        mApp.getApi().confirmShopCarOrder(mApp.getUser().getToken(), getCarIDStrings(), mUserRealName, mUserPhone, mUserAddress, mUserDeliveryTime, mUserRemark, new HttpRequestCallback<OrderSN>() {
            @Override
            public void onSuccess(int code, String msg, OrderSN data) {
                if (!TextUtils.isEmpty(data.getOrdersn()))
                    BuyerOrderDetailActivity.jumpToOrderDetail(OrderConfirmActivity.this, data.getOrdersn());
            }


            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(OrderConfirmActivity.this, msg);
            }
        });
        closeLoadingDialog();
    }

    /**
     * 获得下单时间数据
     */
    @Background
    void getDeliveryTimeData() {
        showLoadingDialog(this);
        mApp.getApi().getDeliveryTimeData(new HttpRequestCallback<DeliveryTime>() {
            @Override
            public void onSuccess(int code, String msg, DeliveryTime data) {
                mDeliveryTimeData = data;
            }


            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(OrderConfirmActivity.this, msg);
            }
        });
        closeLoadingDialog();
    }


    public class SimpleRecyclerCardAdapter extends BaseAdapter {

        private LayoutInflater mInflater;

        public SimpleRecyclerCardAdapter(Context mCtx) {
            super();
            mInflater = LayoutInflater.from(mCtx);
        }


        @Override
        public int getCount() {
            return mShopCarData == null ? 0 : mShopCarData.size();
        }

        @Override
        public ShopCarItem getItem(int position) {
            return mShopCarData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final OrderHeadViewHolder holder;
            if (convertView == null) {
                holder = new OrderHeadViewHolder();
                convertView = mInflater.inflate(R.layout.item_shop_car_product_list, null);
                holder.tvCarName = (TextView) convertView.findViewById(R.id.item_product_name);
                holder.tvCarDetail = (TextView) convertView.findViewById(R.id.item_product_detail);
                convertView.setTag(holder);
            } else {
                holder = (OrderHeadViewHolder) convertView.getTag();
            }
            holder.tvCarDetail.setText("¥ " + mShopCarData.get(position).getPrice() + "*" + mShopCarData.get(position).getNum());
            holder.tvCarName.setText(mShopCarData.get(position).getName());


            return convertView;
        }


    }


    static class OrderHeadViewHolder {
        public TextView tvCarName;
        public TextView tvCarDetail;

    }


}
